package main

import (
	"context"
	"fmt"
	"sync"
	"time"
)

var wg sync.WaitGroup

func cupInfo(ctx context.Context) {
	defer wg.Done()
	ctx2, _ := context.WithCancel(ctx)
	go memoryInfo(ctx2)
	for {
		select {
		case <-ctx.Done():
			fmt.Println("监控CPU退出")
			return
		default:
			time.Sleep(time.Second)
			fmt.Println("获取CPU信息成功")
		}
	}
}

func memoryInfo(ctx context.Context) {
	defer wg.Done()
	for {
		select {
		case <-ctx.Done():
			fmt.Println("监控内存退出")
			return
		default:
			time.Sleep(time.Second)
			fmt.Println("获取内存信息成功")
		}
	}
}

func main() {
	wg.Add(2)
	ctx, cancel := context.WithCancel(context.Background())
	go cupInfo(ctx)

	time.Sleep(time.Second * 6)
	cancel()
	wg.Wait()
}
